package com.ruoyi.jjyh.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.jjyh.domain.*;
import com.ruoyi.jjyh.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品发布Controller
 * 
 * @author ruoyi
 * @date 2020-11-20
 */
@Controller
@RequestMapping("/phone/jjyh/goodsrelease")
public class JjyhGoodsreleasePhoneController extends BaseController
{

    @Autowired
    private IJjyhGoodsreleaseService jjyhGoodsreleaseService;

    @Autowired
    private IJjyhUserService jjyhUserService;

    @Autowired
    private ISysDtAreaService sysDtAreaService;

    @Autowired
    private IJjyhCarService jjyhCarService;


    @Autowired
    private IJjyhMassageService jjyhMassageService;




    /**
     * 获取省市县
     * @param pid
     * @return
     */
    @RequestMapping("/getAreaByPid")
    @ResponseBody
    public AjaxResult getAreaByPid(String pid){
        pid = EmptyUtils.isEmpty(pid)?"0":pid;
        SysDtArea area = new SysDtArea();
        area.setAreaParentId(pid);
        return success("获取成功", sysDtAreaService.selectSysDtAreaList(area));
    }

    /**
     * 获取地址
     * @return
     */
    @RequestMapping("/getArea")
    @ResponseBody
    public AjaxResult getArea(){
        return success("获取成功", sysDtAreaService.selectAreaTree());
    }

    /**
     * 发布产品
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/saveGoods")
    @ResponseBody
    public AjaxResult saveGoods(HttpServletRequest request, HttpServletResponse response){
        String userId = request.getParameter("userId");
        JjyhUser user = jjyhUserService.selectJjyhUserById(userId);
        if(EmptyUtils.isEmpty(user.getUserIdcard())){
            return error("用户未认证");
        }

        JjyhGoodsrelease goods = new JjyhGoodsrelease();
        goods.setId(IdWorker.getId());
        goods.setUserid(userId);
        goods.setUserType(request.getParameter("userType"));//用户类型 个人 企业
        goods.setGoodsTitle(request.getParameter("goodsTitle"));//标题
        goods.setGoogsDesc(request.getParameter("goodsDesc"));//描述内容
        goods.setGoodsPic(request.getParameter("goodsPic"));//商品图片，多个以|隔开
        goods.setIsNewgoods(request.getParameter("isNewGoods"));//新品闲置（全新，九成新，八成新，七成新，七成新以下）
        goods.setGoodsClass(request.getParameter("goodsClass"));//一级分类id
        goods.setGoodsClassTwo(request.getParameter("goodsClassTwo"));//二级分类id
        goods.setGoodsClassThree(request.getParameter("goodsClassThree"));//三级分类id
        goods.setBeginCount(Integer.valueOf(request.getParameter("beginCount")));//起换量
        goods.setStockCount(Integer.valueOf(request.getParameter("stockCount")));//库存量
        goods.setShelfLife(request.getParameter("shelfLife"));//保质期
        goods.setProductDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD, request.getParameter("produntDate")));//生产日期 格式 2020-11-21
        goods.setGoodsUnit(request.getParameter("goodsUnit"));//产品单位
        goods.setGoodsPrice(new BigDecimal(request.getParameter("goodsPrice")));//产品价格
        goods.setReleaseProv(request.getParameter("releaseProv"));//省份编码
        goods.setReleaseProvname(request.getParameter("releaseProvname"));//省份名称
        goods.setReleaseCity(request.getParameter("releaseCity"));//城市编码
        goods.setReleaseCityname(request.getParameter("releaseCityname"));//城市名称
        goods.setCurrentAddress(request.getParameter("currentAddress"));//当前地址
        goods.setExchangeClass(request.getParameter("exchangeClass"));//想要换的产品 分类 第三级别
        goods.setExchangeGoods(request.getParameter("exchangeGoods"));//相互换的产品
        goods.setGoodsStatus("审核中");
        goods.setCreateTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setLat(request.getParameter("lat"));//纬度
        goods.setLon(request.getParameter("lon"));//经度

        jjyhGoodsreleaseService.insertJjyhGoodsrelease(goods);

        JjyhMassage massage = new JjyhMassage();
        massage.setId(IdWorker.getId());

        massage.setUserId(userId);
        massage.setType("1");
        massage.setTitle("系统消息");
        massage.setContent("您已经成功发布一条商品交换信息，后台审核等待时间为1-2个工作日，谢谢您的使用");
        jjyhMassageService.insertJjyhMassage(massage);

        return success("发布成功");
    }


    /**
     * 修改产品
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/updateGoods")
    @ResponseBody
    public AjaxResult updateGoods(HttpServletRequest request, HttpServletResponse response){
        String userId = request.getParameter("userId");
        JjyhUser user = jjyhUserService.selectJjyhUserById(userId);
        if(EmptyUtils.isEmpty(user.getUserIdcard())){
            return error("用户未认证");
        }

        JjyhGoodsrelease goods = new JjyhGoodsrelease();
        goods.setId(request.getParameter("id"));
        goods.setUserid(userId);
        goods.setUserType(request.getParameter("userType"));//用户类型 个人 企业
        goods.setGoodsTitle(request.getParameter("goodsTitle"));//标题
        goods.setGoogsDesc(request.getParameter("goodsDesc"));//描述内容
        goods.setGoodsPic(request.getParameter("goodsPic"));//商品图片，多个以|隔开
        goods.setIsNewgoods(request.getParameter("isNewGoods"));//新品闲置（全新，九成新，八成新，七成新，七成新以下）
        goods.setGoodsClass(request.getParameter("goodsClass"));//一级分类id
        goods.setGoodsClassTwo(request.getParameter("goodsClassTwo"));//二级分类id
        goods.setGoodsClassThree(request.getParameter("goodsClassThree"));//三级分类id
        goods.setBeginCount(Integer.valueOf(request.getParameter("beginCount")));//起换量
        goods.setStockCount(Integer.valueOf(request.getParameter("stockCount")));//库存量
        goods.setShelfLife(request.getParameter("shelfLife"));//保质期
        goods.setProductDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD, request.getParameter("produntDate")));//生产日期 格式 2020-11-21
        goods.setGoodsUnit(request.getParameter("goodsUnit"));//产品单位
        goods.setGoodsPrice(new BigDecimal(request.getParameter("goodsPrice")));//产品价格
        goods.setReleaseProv(request.getParameter("releaseProv"));//省份编码
        goods.setReleaseProvname(request.getParameter("releaseProvname"));//省份名称
        goods.setReleaseCity(request.getParameter("releaseCity"));//城市编码
        goods.setReleaseCityname(request.getParameter("releaseCityname"));//城市名称
        goods.setCurrentAddress(request.getParameter("currentAddress"));//当前地址
        goods.setExchangeClass(request.getParameter("exchangeClass"));//想要换的产品 分类 第三级别
        goods.setExchangeGoods(request.getParameter("exchangeGoods"));//相互换的产品
        goods.setGoodsStatus("审核中");
        goods.setCreateTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setLat(request.getParameter("lat"));//纬度
        goods.setLon(request.getParameter("lon"));//经度

        jjyhGoodsreleaseService.updateJjyhGoodsrelease(goods);
        return success("发布成功");
    }


    /**
     * 查询产品列表
     * @param pageNumber 分页页码 1，2，3，...
     * @param pageSize 每页条数
     * @param typeId 分类id 一级分类id
     * @param cityId 城市id
     * @param userGroup 用户组  企业清库（userGruop=企业）
     * @param isNew  换限制（isNew=闲置）
     * @param startPrice 价格区间 开始
     * @param endPrice 价格区间 结束
     * @param name 名称
     * @param userType 用户等级 1注册用户  2包月用户  3包年用户
     * @param classType 换产品 classType=产品    换服务 classType=服务
     * @param newType 新旧程度 全新，九成新，八成新，七成新，七成新以下
     * @param lat 纬度
     * @param lon 经度
     * @param sort 排序 1价格升序 2价格降序
     * @return
     */
    @RequestMapping("/getGoodsList")
    @ResponseBody
    public AjaxResult getGoodsList(int pageNumber, int pageSize,String typeId, String cityId, String userGroup, String isNew, String startPrice, String endPrice,
                                String name, String userType, String classType, String newType, String lat, String lon, String sort){
        Map<String, Object> map = new HashMap<>();
        map.put("pageNumber", (pageNumber-1) * pageSize);
        map.put("pageSize", pageSize);
        map.put("typeId", typeId);
        if(EmptyUtils.isNotEmpty(cityId)){
            cityId = cityId.substring(0, 4);
            map.put("cityId", cityId);
        }
        map.put("userGroup", userGroup);
        map.put("isNew", isNew);
        map.put("startPrice", startPrice);
        map.put("endPrice", endPrice);
        map.put("name", name);
        map.put("sort", sort);
        if(EmptyUtils.isNotEmpty(userType)){
            switch (userType){
                case "1" :
                    map.put("userType", "834598172247461888");
                    break;
                case "2" :
                    map.put("userType", "834598284730306560");
                    break;
                case "3" :
                    map.put("userType", "834598356696174592");
                    break;
                default:break;

            }
        }

        map.put("classType", classType);
        map.put("newType", newType);
        map.put("lat", lat);
        map.put("lon", lon);

        List<JjyhGoodsrelease> list = jjyhGoodsreleaseService.selectGoodsList(map);
        if(list.size() > 0){
            return success("获取成功", list);
        }
        return error("暂无数据");
    }

    /**
     *  获取首页爱换头条
     * @return
     */
    @RequestMapping("/getHeadlines")
    @ResponseBody
    public AjaxResult getHeadlines(){
        Map<String, Object> map = new HashMap<>();
        map.put("pageNumber", 0);
        map.put("pageSize", 10);
        map.put("userType", "834598356696174592");
        map.put("lat", "34.72468");
        map.put("lon", "113.6401");

        return success("获取成功", jjyhGoodsreleaseService.selectGoodsList(map));
    }

    /**
     * 查询商品详情
     * @param id
     * @param lat
     * @param lon
     * @return
     */
    @RequestMapping("/getGoodsById")
    @ResponseBody
    public AjaxResult getGoodsById(String id, String lat, String lon, String userId){
        if(EmptyUtils.isEmpty(lat)){
            lat = "34.72468";
            lon = "113.6401";
        }
        JjyhGoodsrelease goodsrelease = jjyhGoodsreleaseService.selectGoodsById(id, lat, lon);
        JjyhGoodsrelease goods = new JjyhGoodsrelease();
        goods.setId(id);
        goods.setViews(goodsrelease.getViews() + 1);
        jjyhGoodsreleaseService.updateJjyhGoodsrelease(goods);

        return success("获取成功", goodsrelease);
    }


    /**
     * 添加购物车
     * @param goodsId
     * @param userId
     * @return
     */
    @RequestMapping("/saveCar")
    @ResponseBody
    public AjaxResult saveCar(String goodsId, String userId){
        JjyhCar car = new JjyhCar();
        car.setGoodsId(goodsId);
        car.setUserId(userId);

        List<JjyhCar> car1 = jjyhCarService.selectJjyhCarList(car);
        if(car1.size() > 0){
            car.setId(car1.get(0).getId());
            car.setNum(car1.get(0).getNum() + 1);
            jjyhCarService.updateJjyhCar(car);
        }else{

            car.setId(IdWorker.getId());
            car.setNum(1);
            car.setGoodsId(goodsId);
            car.setUserId(userId);
            car.setCreateTime(new Date());
            jjyhCarService.insertJjyhCar(car);
        }
        return success("操作成功");
    }

    /**
     * 获取我的购物车
     * @param userId
     * @return
     */
    @RequestMapping("/getCarList")
    @ResponseBody
    public AjaxResult getCarList(String userId){
        return success("操作成功", jjyhCarService.selectCarByUserId(userId));
    }

    /**
     * 修改购物车数量
     * @param id
     * @param num
     * @return
     */
    @RequestMapping("/updateCar")
    @ResponseBody
    public AjaxResult updateCar(String id, Integer num){
        JjyhCar car = new JjyhCar();
        car.setId(id);
        car.setNum(num);
        jjyhCarService.updateJjyhCar(car);
        return success("操作成功");
    }

    /**
     * 删除购物车商品
     * @param ids
     * @return
     */
    @RequestMapping("/deleteCar")
    @ResponseBody
    public AjaxResult deleteCar(String ids){
        jjyhCarService.deleteJjyhCarByIds(ids);
        return success("操作成功");
    }


    /**
     * 获取我的商品列表
     * @param userId
     * @param status 产品状态（1上架中，2下架中，3审核中，4未通过）
     * @return
     */
    @RequestMapping("/getMyGoods")
    @ResponseBody
    public AjaxResult getMyGoods(String userId, String status){
       JjyhGoodsrelease goodsrelease = new JjyhGoodsrelease();
       goodsrelease.setUserid(userId);
       switch (status){
           case "1":goodsrelease.setGoodsStatus("上架");break;
           case "2":goodsrelease.setGoodsStatus("下架");break;
           case "3":goodsrelease.setGoodsStatus("审核中");break;
           case "4":goodsrelease.setGoodsStatus("审核未通过");break;
       }
        return success("获取成功", jjyhGoodsreleaseService.selectJjyhGoodsreleaseList(goodsrelease));
    }

    /**
     * 删除商品
     * @param goodsId
     * @return
     */
    @RequestMapping("/delGoods")
    @ResponseBody
    public AjaxResult delGoods(String goodsId){
        JjyhGoodsrelease goodsrelease = new JjyhGoodsrelease();
        goodsrelease.setId(goodsId);
        goodsrelease.setDelflag("0");
        return success("获取成功", jjyhGoodsreleaseService.updateJjyhGoodsrelease(goodsrelease));
    }

    /**
     * 商品上架  下架
     * @param goodsId
     * @param status 产品状态（1上架，2下架）
     * @return
     */
    @RequestMapping("/updateGoodsStatus")
    @ResponseBody
    public AjaxResult updateGoodsStatus(String goodsId, String status){
        JjyhGoodsrelease goodsrelease = new JjyhGoodsrelease();
        goodsrelease.setId(goodsId);
        switch (status){
            case "1":goodsrelease.setGoodsStatus("上架");break;
            case "2":goodsrelease.setGoodsStatus("下架");break;
            case "3":goodsrelease.setGoodsStatus("审核中");break;
            case "4":goodsrelease.setGoodsStatus("审核未通过");break;
        }
        return success("获取成功", jjyhGoodsreleaseService.updateJjyhGoodsrelease(goodsrelease));
    }

    /**
     * 获取单位
     * @return
     */
    @RequestMapping("/getGoodsUnit")
    @ResponseBody
    public AjaxResult getGoodsUnit(){
        return success("获取成功", jjyhGoodsreleaseService.selectUnit());
    }
}

